// Cookie
function createCookie(a,b,c){if(c){var d=new Date();d.setTime(d.getTime()+(c*24*60*60*1000));var e="; expires="+d.toGMTString()}else{var e=""}document.cookie=a+"="+b+e+"; path=/"}function readCookie(a){var b=a+"=";var d=document.cookie.split(';');for(var i=0;i<d.length;i++){var c=d[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(b)==0)return c.substring(b.length,c.length)}return null}function eraseCookie(a){createCookie(a,"",-1)};

// Bottom of page
(function($) {
	var $window = $(window),
	$body = $(document.body),
	$dataAuthor = $('[data-author="Taufik Nurrohman$"]'),
	$topLink = $('#gotop'),
	$checkerBox = $('#reader'),
	$viewPort = $('html, body'),
	$jumpLink = $('.local-permalink'),
	$ulSpy = $('ul.spy'),
	$blogStatus = $('#status'),
	$updateBoard = $blogStatus.find('.section'),
	$nav = $('#taufik'),
	$shockElem = $body.find('*'),
	$pageLoader = $('#page-loader'),
	$openFrame = $('.openFrame'),
	$myComments = $('#comments'),
	$ansButton = $('.answer-this-comment'),
	$commentForm = $('#comment-form'),
	$commentEditor = $('#comment-editor'),
	$commentVideo = $myComments.find('.video'),
	$fiddleScreen = $('.jsfiddle-demo'),
	$myDescription = $('abbr, acronym'),
	$emoBar = $('#emobar'),
	$triggerDialog = $('.trigger-dialog'),
	$sidebarWrapper = $('#sidebar-wrapper'),
	$labelWidget = $sidebarWrapper.find('#Label1'),
	$togglePre = $('#togglePre'),
	$topRibbon = $('#top-ribbon'),
	$searchBox = $('#cse-search-box'),
	$subscribeForm = $topRibbon.find('#subscribeform'),
	$subscribeButton = $('.subscribe'),
	$closeForm = $('.closeform'),
	$opener = $('#openab'),
	$closer = $('#closeab'),
	$aboutPanel = $('#about'),
	$fadeElem = $('#cse-search-box, .ad-banner, #main, #reader, #alexa'),
	$slideElem = $('#header, #main-wrapper, #sidebar-wrapper,#content-wrapper,  #ad-wrapper, .sidebarbox'),
	urlHash = (window.location.hash) ? window.location.hash.substr(1) : '';

	// Some elements...
	$body.removeClass('init').append('<div id="alert-box" class="hidden"><div class="message"></div></div><span id="loadingtext"></span>').on("click", function() {
		$('.emoKey').remove();
	});
   
  tagReplaceBody('em[class="gambar"]','<figure class="separator center"><img alt="','</figcaption></figure>');

	var $alertBox = $('#alert-box'), $loadingText = $('#loadingtext');
	// Dialog
	function makeDialog(a,b,c) {
		var c = (b !== false) ? b : '', d = (b !== false) ? '<div class="button-group"><button class="close">'+c+'</button></div>' : '';
		$alertBox.fadeIn(600).children().css('width',c).html(a+d);
		if (b !== false) {
			$alertBox.on("click", ".close", function() {
				$alertBox.fadeOut();
			});
		}
	}
	// Tag Replace
	function tagReplaceV(a,b,c) {
		$(a).replaceWith(function() {
       var links = $(this).html();
       var links2=links.replace("http://blog.pustakaflash.com","http://www.pustakaflash.net");
       links=links.replace("http://blog.pustakaflash.com","http://www.pustakaflash.net");
       var tes = links.lastIndexOf('/') + 1,tes2= links.lastIndexOf('.');
        links = decodeURIComponent(links.substring(tes,tes2));
        links= links.replace(/[\+\-\_]/g, " ");
        
        return $(b+links2+ '">'+links+c);
		});
	}
    function tagReplace(a,b,c) {
		$(a).replaceWith(function() {
       var links =$(this).html();
     	return $(b+links+c);
		});
	}
     
    function tagReplaceBody(a,b,c) {
		$(a).replaceWith(function() {
      var links = $(this).html();
      var jdl = $(this).html();
       var tes = jdl.lastIndexOf('/') + 1,tes2= jdl.lastIndexOf('.');
        jdl = decodeURIComponent(jdl.substring(tes,tes2));
        jdl= jdl.replace(/[\+\-\_]/g, " ");
      return $(b+links+'" src="'+links+'"/><figcaption><p><em rel="note"><strong>Gambar: '+jdl+'</strong></em></p></figcaption>'+c);
		});
	}
   
   
   function getTitle(str) {

    var a = str.lastIndexOf('/') + 1,b = str.lastIndexOf('.');
    str = decodeURIComponent(str.substring(a, b));
    str = str.replace(/[\+\-\_]/g, " ");
    return str;
}
   function ReplaceV(a,b,c) {
   var value = $myComments.val(); 
    value = value.replace(a, b); // value = 9:61
    $myComments.val(value);
    
   }
   
function blog(str) {
 str=str.replace("http://blog.pustakaflash.com","http://www.pustakaflash.net");
    return str;
}
   
	// View my Profile
	function viewProfile() {
		$('#taufik li ul').slideUp();
		$topRibbon.stop().animate({top:-350}, 700, function() {
			$fadeElem.fadeOut(700, function() {
				$aboutPanel.slideDown(1000, function() {
					$(this).animate({width:"60%"}, 600);
				});
				$slideElem.slideUp(1000);
			});
		});
	}
	function hideProfile() {
		$fadeElem.fadeIn(700, function() {
			$topRibbon.stop().animate({top:0}, 600, function() {
				$aboutPanel.animate({width:"90%"}, 600, function() {
					$(this).slideUp(700);
				});
			});
		});
	}
	$opener.on("click", function() {
		if ($window.scrollTop() > 100) {
			$viewPort.stop().animate({scrollTop:0}, 'slow', viewProfile);
		} else {
			viewProfile();
		}
		return false;
	});
	$closer.on("click", function() {
		$slideElem.slideDown(1000, hideProfile);
		return false;
	});
	// Trigger dialog
	$emoBar.one("click", function() {
		makeDialog($(this).data('dialog'),'OK','370px');
	});
	$triggerDialog.on("click", function() {
		makeDialog($(this).data('dialog'),'Tutup','80%');
		return false;
	});
	// Sliding ribbon based on input focus
	if ($topRibbon.is(':visible')) {
		$searchBox.find('input').focus(function() {
			var ribbonMoveDistance = $topRibbon.outerWidth() - ($searchBox.offset().left - $topRibbon.offset().left) + 17;
			$topRibbon.stop().animate({marginRight:ribbonMoveDistance}, 1000);
		}).focusout(function() {
			$topRibbon.stop().animate({marginRight:0}, 1000);
		});
	}
	// Loading animation
	var siteURL = "http://" + top.location.host.toString(),
		$internalLinks = "a[href^='" + siteURL + "'], a[href^='/'], a[href^='./'], a[href^='../']";
	$('#out-shadow').on("click", $internalLinks, function() {
		$pageLoader.fadeIn(1500).delay(7000).fadeOut(1000);
	});
	$openFrame.on("click", function() {
		var urlFrame = $(this).attr('href');
		$pageLoader.append('<iframe id="frame1" src="' + urlFrame + '" frameborder="0" scrolling="auto"></iframe>').fadeIn(1500).on("click", function() {
			$(this).find('iframe, .atribusiform').remove();
			$(this).slideUp();
		});
		return false;
	});
	// Toggle PRE Tag
	$togglePre.on("change", function() {
		if ($(this).is(':checked')) {
			$body.addClass('prelight');
			createCookie('pre', 'prelight', 1000);
		} else {
			$body.removeClass('prelight');
			eraseCookie('pre', 'prelight');
		}
	});
	if (readCookie('pre')) {
		$body.addClass('prelight');
		$togglePre.prop('checked', true);
	}
	// Show/hide subscribe form
	$subscribeButton.on("click", function() {
		$topRibbon.stop().animate({
			width: 328
		}, 2000, "easeInOutExpo", function() {
			$subscribeForm.fadeIn('slow');
		});
		return false;
	});
	$closeForm.on("click", function() {
		$subscribeForm.fadeOut('slow', function() {
			$topRibbon.stop().animate({
				width: 108
			}, 1000, "easeInOutExpo");
		});
		return false;
	});
	// Accordion sidebar
	$sidebarWrapper.find('.widget-content').hide();
	$sidebarWrapper.find('h2').on("click", function() {
		$sidebarWrapper.find('h2').removeClass('headactive').next().slideUp(900, "easeInOutExpo");
		if ($(this).next().is(':hidden')) {
			$(this).addClass('headactive').next().slideDown(600, "easeInOutExpo");
		}
	}).last().addClass('headactive').next().show();
	// Label widget hover effect
	$labelWidget.find('a').hover(function() {
		$(this).find('.label-count').slideDown(500, "easeOutBounce");
	}, function() {
		$(this).find('.label-count').fadeOut(400, "easeOutQuart");
	});
	// Comments...
	$myComments.on("click", ".emo", function(e) {
		$('.emoKey').remove();
		$(this).after('<input type="text" size="6" class="emoKey" value=" '+this.alt+'" />');
		$('.emoKey').trigger("select");
		e.stopPropagation();
	}).find('.komentar-spam').each(function(allowLinks,commentContents) {
		allowLinks = $(this).find('a:not(.allow)');
		commentContents = $(this).html();
		txtContents = commentContents.replace(/<br>/ig, "\n").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/&lt;pre&gt;/ig, "&lt;i rel=\"pre\"&gt;").replace(/&lt;code&gt;/ig, "&lt;i rel=\"code\"&gt;").replace(/&lt;blockquote&gt;/ig, "&lt;b rel=\"quote\"&gt;").replace(/&lt;h([1-6])&gt;/ig, "&lt;b rel=\"h$1\"&gt;").replace(/&lt;\/(code|pre)&gt;/ig, "&lt;\/i&gt;").replace(/&lt;\/(blockquote|h[1-6])&gt;/ig, "&lt;\/b&gt;");
		if (allowLinks.length) {
			$(this).html('Komentar Anda telah dihapus/disembunyikan untuk alasan keamanan dan kenyamanan pembaca lain. Kemungkinan hal ini terjadi karena Anda menuliskan komentar disertai dengan munculnya tautan-tautan yang tidak diperlukan pembaca/tidak sesuai dengan diskusi. Tapi jika bukan itu masalahnya, Saya harap Anda bersedia mencoba menuliskan komentar Anda kembali tanpa mencantumkan tautan/link aktif yang tidak diperlukan. Berikut ini adalah salinan yang mungkin Anda perlukan dari komentar lama yang baru Anda tuliskan sebelum ini:<textarea spellcheck="false">' + txtContents + '</textarea>Terima kasih banyak atas kontribusi Anda di blog eksperimen ini. Salam, <strong>Administrator <big>&hearts;</big></strong><br>').addClass('deleted-by-js').closest('.cm_wrap').find('.cm_reply a').remove();
		}
	});
	// Comments manipulation
	var $commentImages = $('.incomment');
	$commentImages.each(function(link) {
		link = $(this).attr('src');
		$(this).wrap('<a class="center allow" href="'+link+'" target="_blank"></a>');
		$(this).attr('src', link.replace(/\/s(640|1600)/g, "/s400"));
	});
	tagReplace('b[rel="quote"]','<blockquote><p>','</p></blockquote>');
  tagReplaceV('i[rel="anchor"]','<p><em rel="note"><strong>Artikel: <a href="','</a></strong></em></p>');
	tagReplace('i[rel="pre"]','<pre class="numbered"  rel="ACTIONSCRIPT 3"><code class="JavaScript">','</code></pre>');
  ReplaceV("http://blog.pustakaflash.com","http://www.pustakaflash.net")
	var $codeRef = $('div > code,p > code,td > code');
	$codeRef.each(function() {
		$(this).wrapInner('<a class="allow" title="Telusuri makna kode ini" href="/p/cari-artikel.html?q=' + encodeURIComponent($(this).text()) + '" target="_blank"></a>');
	});
	// Thread comment form
	var source = ($commentEditor.length) ? $commentEditor.attr('src').split('#') : "";
	$ansButton.on("click", function() {
		$alertBox.hide();
		$commentEditor.css('opacity',0);
		$ansButton.removeClass('clicked');
		$(this).addClass('clicked');
		var start = source[0], end = source[1],
			replyFrame = start + '&parentID=' + $(this).data('rel').substr(1) + '#' + end,
			$goTo = $(this).closest('.cm_wrap');
		$viewPort.scrollTop($goTo.offset().top - 30);
		$loadingText.html('<span>Memuat...</span>');
		$commentForm.appendTo($goTo);
		$commentEditor.attr('src', replyFrame).on("load", function() {
			$(this).css('opacity', 1);
			$loadingText.html('');
		});
		return false;
	});
	$myComments.on("click", "#cancel-answer", function() {
		var ofs = $('#comment-editor-src').attr('href');
		$loadingText.html('<span>Memuat...</span>');
		$commentForm.appendTo($myComments);
		$commentEditor.css('opacity', 0).attr('src', ofs + '#' + source[1]).on("load", function() {
			$(this).css('opacity', 1);
			$loadingText.html('');
		});
		$ansButton.removeClass('clicked');
		return false;
	});
	$fiddleScreen.each(function(url) {
		url = $(this).data('src');
		$(this).after('<iframe class="jsfiddle-demo loader" src="' + url + '"></iframe>').remove();
	});
	// Toolpik
	$myDescription.hover(function(e) {
		var winWidth = $window.width(),
			winHeight = $window.height();
		$(this).append('<div id="toolpik"><div id="nurrohman"></div><div style="clear:both;"></div></div>');
		$('#nurrohman', '#toolpik').html($(this).attr('title'));
		$(this).removeAttr('title');
		var toolpikWidth = $("#toolpik").outerWidth(),
			toolpikHeight = $("#toolpik").outerHeight(),
			top = e.clientY - toolpikHeight / 2,
			left = e.clientX - toolpikWidth / 2;
		if (top + toolpikHeight > winHeight) {
			top = winHeight - toolpikHeight - 50;
		} else if (top <= 0) {
			top = 10;
		}
		if (left + toolpikWidth > winWidth) {
			left = winWidth - toolpikWidth - 50;
		} else if (left <= 0) {
			left = 10;
		}
		$('#toolpik').delay(600).fadeIn(1000, function() {
			$(this).delay(600).animate({top:top-70,left:left}, 2000, "easeOutBack", function() {
				$(this).animate({top:top}, 400);
			});
		});
	}, function() {
		$(this).attr('title', $('#nurrohman').html());
		$('#nurrohman').parent().remove();
	});
	// Update Board
	$blogStatus.hover(function() {
		$updateBoard.filter(':not(:animated)').delay(1000).show('slow', "easeOutBack");
	}, function() {
		$updateBoard.stop(true, true).delay(1000).hide('slow', "easeInExpo");
	}).children('strong').toggle(function() {
		$updateBoard.show('slow', "easeOutBack");
	}, function() {
		$updateBoard.hide('slow', "easeInExpo");
	});
	// Drop down menu
	function onHover() {
		$nav.find('li').hover(function() {
			$('ul', this).filter(':not(:animated)').slideDown(600, "easeOutBounce").parent().addClass('active');
		}, function() {
			$('ul', this).slideUp(600, "easeInExpo").parent().removeClass('active');
		});
	} onHover();
	$nav.on("mouseleave", onHover).find('.hidden').removeClass('hidden').prev().on("click", function() {
		$(this).next().toggle().parent().toggleClass('active').off("hover");
		return false;
	});
	
	$jumpLink.on("click", function() {
		var distance = ($('#' + this.hash.substr(1)).length) ? $('#' + this.hash.substr(1)).offset().top : $('.' + this.hash.substr(1)).first().offset().top;
		$viewPort.animate({scrollTop:distance-30}, 'slow');
		return false;
	});
	if (!readCookie('disable-notification')) {
		$loadingText.html('<iframe class="notif-count" src="http://projekpustaka.googlecode.com/svn/trunk/notif.html"></iframe>');
	}
	// Top link
	$window.on("scroll", function() {
		if ($(this).scrollTop() > 0) {
			$topLink.stop().animate({bottom:0,right:0}, 600);
			$checkerBox.stop().animate({right:50}, 1000);
		} else {
			$topLink.stop().animate({bottom:-40,right:-40}, 600);
			$checkerBox.stop().animate({right:20}, 1000);
		}
	// Preloading...
	}).on("load", function() {
		// Fix my comment jump links bug!
		if(window.location.hash && window.location.hash.indexOf('#c') !== -1) {
			var $targetElem = $('.' + urlHash), scrollDistance = $targetElem.offset().top-30;
			$viewPort.animate({scrollTop:scrollDistance}, 4000, function() {
				$targetElem.find('.comment_body').css('border','2px solid #ff0');
				$targetElem.find('.avatar-image-container').css({'padding':0,'border':'5px solid #ff0'});
			});
		}
		$commentVideo.each(function() {
			if(/youtube\.com\/embed/.test($(this).data('src'))) {
				$(this).attr('src', $(this).data('src'));
			} else {
				$(this).removeAttr('src').css('background','#900 url(http://hompimpa.googlecode.com/svn/trunk/personal/images/iframe-fallback.png) no-repeat 50% 50%');
			}
		});
	});
	$topLink.removeAttr('href').on("click", function() {
		$viewPort.stop().animate({scrollTop:0}, 970, "easeInOutQuad");
		return false;
	});
})(jQuery);


